﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using ReportingEngine;
using System.IO;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Data.SqlClient;
using System.Data;
using TSL_Tools.SqlTools;


namespace VSLT_Reporting
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private TSL_ReportingEngine re;
        private List<int> selectedRuns;
        private int currentlyHighlightedRunId = -1;
        public AppConfiguration settings;
        private string mostRecentSqlQuery = "";
        private List<string> machineNamesForRun = new List<string>();

        private List<ScoreCardItem> scoreCardFields = new List<ScoreCardItem>();

        private DataTable _scoreCardMetrics;
        private DataTable _scoreCardPerfmon;

        private bool appIsInitializing = true;

        private ReportGenerator.CellHighlighting cellHighlighting = new ReportGenerator.CellHighlighting();

        TalkToSql tts;

        // -- INITIALIZE handlers -------------------------------------------------------------
        #region initialization
        public MainWindow()
        {
            // Sleep for 3 seconds to allow splash screen to display
            //Thread.Sleep(3000);   

            AppDomain.CurrentDomain.UnhandledException+=CurrentDomain_UnhandledException;

            InitializeComponent();
            this.WindowState = System.Windows.WindowState.Maximized;
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //throw new NotImplementedException();
          
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //PlayWithSql();
            LoadAppSettings();
            InitializeTheApp();
            selectedRuns = new List<int>();
            InitializeHelpFileTopics();
            this.dgMainResults.LoadingRow += new EventHandler<System.Windows.Controls.DataGridRowEventArgs>(dataGrid_LoadingRow);
            appIsInitializing = false;
            cellHighlighting.ReadHighlightSettingsFromXmlFile(Properties.Settings.Default.ChartObjectFileName);
        }
        
        private void PlayWithSql()
        {
            //string sqlConnString = "Data Source=junctionsql;Initial Catalog=northwind;Integrated Security=True";
            string sqlConnString = "Data Source=(localdb)\v11.0;Initial Catalog=LoadTest2010;Integrated Security=True";
            using (SqlConnection sqlConn = new SqlConnection(sqlConnString))
            {
                sqlConn.Open();

                string sqlCmd = @"SELECT * FROM LoadTestRun";
                using (SqlCommand cmd = new SqlCommand(sqlCmd, sqlConn))
                {
                    cmd.ExecuteReader();
                }
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            settings.SaveConfigValues();
            SaveExtendedSettings();
        }
        #endregion

        // -- HELP Button Handlers -----------------------------------------------------------
        #region HELP Button
        private void btnMenuHelpTopic0_Click(object sender, RoutedEventArgs e)
        {
            LoadHelpFile("HelpFiles\\00_Getting Started.rtf", ".rtf");
        }

        private void btnMenuHelpTopic1_Click(object sender, RoutedEventArgs e)
        {
            LoadHelpFile("HelpFiles\\HelpFile_ResultsDifferences.rtf", ".rtf");
        }

        private void btnMenuHelpTopic2_Click(object sender, RoutedEventArgs e)
        {
            LoadHelpFile("HelpFiles\\HelpFile_ResultsStorage.rtf", ".rtf");
        }

        private void btnMenuHelpTopic3_Click(object sender, RoutedEventArgs e)
        {
            LoadHelpFile("HelpFiles\\HelpFile_WarmupCooldown.rtf", ".rtf");
        }

        private void btnMenuHelpTopic4_Click(object sender, RoutedEventArgs e)
        {
            LoadHelpFile("HelpFiles\\", ".rtf");
        }

        private void lvHelpTopics_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ChangeDisplayedHelpTopic();
        }

        #endregion

        // -- OPTIONS tab handlers -----------------------------------------------------------
        #region OPTIONS
        private void btnOptionsSet_Click(object sender, RoutedEventArgs e)
        {
            ConfigureAppSettings();
        }

        private void btnOptionsSave_Click(object sender, RoutedEventArgs e)
        {
            SaveAppSettings();
        }

        private void btnResetAppConfig_Click(object sender, RoutedEventArgs e)
        {
            ResetAppSettings();
        }

        private void btnUpdateSqlCode_Click(object sender, RoutedEventArgs e)
        {
            InstallSqlCodeOnDatabase();
        }

        private void btnLoadRunResults_Click(object sender, RoutedEventArgs e)
        {
            LoadSampleTemplate();
        }

        private void btnSaveRunResults_Click(object sender, RoutedEventArgs e)
        {
            SaveSampleTemplate();
        }
        #endregion

        // -- HOME tab handlers ---------------------------------------------------------------
        #region HOME
        private void btnGetRuns_Click(object sender, RoutedEventArgs e)
        {
            // Added by SeanJ
            // This is a temporary workaround so that the database connection isn't used at app startup.
            //CheckConnectivityAndDBVersion(true);

            PopulateDataGridWithRuns();
            //tsslMessage.Content = re.AddConstantLoadIntervals();
        }

        private void btnGetScorecard_Click(object sender, RoutedEventArgs e)
        {
            GetScorecardInfo();
        }

        private void btnShowRunResults_Click(object sender, RoutedEventArgs e)
        {
            DataGridSelectionChanged();
        }

        private void btnShowLoadTest_Click(object sender, RoutedEventArgs e)
        {
            showLoadTestForHighlightedRun();
        }

        private void btnShowAnalysisNotes_Click(object sender, RoutedEventArgs e)
        {
            ShowAnalysisNotes();
        }

        private void btnSaveLoadTestFile_Click(object sender, RoutedEventArgs e)
        {
            tsslMessage.Content = re.SaveLoadTestXML(currentlyHighlightedRunId, Properties.Settings.Default.FolderToStoreResults + "Run_" + currentlyHighlightedRunId.ToString() + ".loadtest");
        }

        private void btnGenerateReport_Click(object sender, RoutedEventArgs e)
        {
            GenerateTheReport();
        }

        private void btnPrintReport_Click(object sender, RoutedEventArgs e)
        {
            PrintTheReport();
        }

        private void btnSaveReport_Click(object sender, RoutedEventArgs e)
        {
            SaveTheReport();
        }

        private void btnAddTestIntervalTablesToReportTab_Click(object sender, RoutedEventArgs e)
        {
            AddTestIntervalTablesToReport();
        }

        private void btnAddTransIntervalTablesToReportTab_Click(object sender, RoutedEventArgs e)
        {
            AddTransactionIntervalTablesToReport();
        }

        private void btnAddPageIntervalTablesToReportTab_Click(object sender, RoutedEventArgs e)
        {
            AddPageIntervalTablesToReport();
        }

        private void btnAddPerfmonIntervalTablesToReportTab_Click(object sender, RoutedEventArgs e)
        {
            AddPerfmonIntervalTablesToReport("", "Processor", "% Processor Time", "_Total", "Processor Values for 'constant load' Intervals");
        }

        private void btnDatabaseInformation_Click(object sender, RoutedEventArgs e)
        {
            GetDatabaseInformation();
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            ExitApplication();
        }
        #endregion

        // -- RUNS tab handlers ---------------------------------------------------------------
        #region RUNS
        private void btnToday_Click(object sender, RoutedEventArgs e)
        {
            BuildListOfHighlightedRuns(RunsToRetrieve.TodayOnly);
        }

        private void btnHighlighted_Click(object sender, RoutedEventArgs e)
        {
            BuildListOfHighlightedRuns(RunsToRetrieve.SelectedDay);
        }

        private void btnHighlightedRange_Click(object sender, RoutedEventArgs e)
        {
            BuildListOfHighlightedRuns(RunsToRetrieve.SelectedRange);
        }

        private void btnSelectedRuns_Click(object sender, RoutedEventArgs e)
        {
            BuildListOfHighlightedRuns(RunsToRetrieve.SelectedRuns);
        }

        private void btnGenerateFiltered_Click(object sender, RoutedEventArgs e)
        {
            BuildListOfFilteredRuns();
        }
        #endregion

        // -- TABLES tab handlers -------------------------------------------------------------
        #region TABLES
        private void srGenTest_Click(object sender, RoutedEventArgs e)
        {
            GenerateRunData_TEST();
        }

        private void srGenTransaction_Click(object sender, RoutedEventArgs e)
        {
            if ((bool)btnToggleCombineNames.IsChecked)
            {
                GenerateRunData_TRANSACTION_COMBINED();
            }
            else
            {
                GenerateRunData_TRANSACTION();
            }
        }

        private void srGenPage_Click(object sender, RoutedEventArgs e)
        {
            if ((bool)btnToggleCombineNames.IsChecked)
            {
                GenerateRunData_PAGE_COMBINED();
            }
            else
            {
                GenerateRunData_PAGE();
            }
        }

        private void srGenPerfmon_Click(object sender, RoutedEventArgs e)
        {
            GenerateRunData_PERFMON();
        }

        private void srUseIntervals_Click(object sender, RoutedEventArgs e)
        {
            cbIntervalColumn.IsEnabled = (bool)btnToggleUseIntervals.IsChecked;
            //tbIntervalValue.IsEnabled = (bool)btnToggleUseIntervals.IsChecked;
        }

        private void srCombineNames_Click(object sender, RoutedEventArgs e)
        {
            CombineNamesButtonToggled();
        }

        private void srIncludeFailed_Click(object sender, RoutedEventArgs e)
        {
            IncludeFailedIterationsButtonToggled();
        }
        #endregion

        // -- CHARTS tab handlers -------------------------------------------------------------
        #region CHARTS
        private void TestTheCharting_Click(object sender, RoutedEventArgs e)
        {
            GetChartObjectsFromXmlFile();
            GetChartObjectColorsFromXmlFile();
            AddChartObjectsToSeriesSets();
            BuildChartsForTesting();
        }

        private void btnChartLoadTemplate_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.InitialDirectory = Properties.Settings.Default.FolderToStoreResults;

            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();
            if(result == true)
            {
                Chart chart = this.FindName("MyWinformChart") as Chart;
                LoadChartTemplate(ref chart, dlg.FileName);
            }

        }

        private void btnChartSaveTemplate_Click(object sender, RoutedEventArgs e)
        {
            Chart chart = this.FindName("MyWinformChart") as Chart;
            SaveChartTemplate(ref chart, "c:\\temp\\TempChart.xml",false);
        }

        private void btnSaveChartAsBitmap_Click(object sender, RoutedEventArgs e)
        {
            CopyChartToClipboard();
        }
        #endregion

        // -- QUERIES tab handlers ------------------------------------------------------------
        #region Queries
        private void btnQuery1_Click(object sender, RoutedEventArgs e)
        {
            if(selectedRuns.Count == 1)
            {
                bool hasIntervals = re.listOfRuns[currentlyHighlightedRunId].resultTypes.HasFlag(ResultTypesStoredInLoadTest.ContainsStepLoad);
                bool detailedTimingAvailable = re.listOfRuns[currentlyHighlightedRunId].resultTypes.HasFlag(ResultTypesStoredInLoadTest.ContainsDetailedTimingInfo);
                TimeSpan ts = new TimeSpan();
                if (hasIntervals && detailedTimingAvailable)
                    if (queryColumnSelectedValue.SelectedValue.ToString().ToLower() == "throughput")
                    {
                        ClearReportTab();
                        DataTable _table = GenerateRunThroughputData_interval_ReturnAsTable(TSL_ReportingEngine.Sql_INTERVAL_PAGETHROUGHPUT, "Page Name", ref ts);
                        AddPageTableToReportTab(_table, cellHighlighting, "Throughput HotSpot Table");
                    }
                    else
                    {
                        ClearReportTab();
                        DataTable _table = GenerateRunData_interval_ReturnAsTable(TSL_ReportingEngine.Sql_INTERVAL_PAGERESULTS, queryColumnSelectedValue.SelectedValue.ToString(), ref ts);
                        AddPageTableToReportTab(_table, cellHighlighting, "Page HotSpot Table");
                    }
            }
            else if(selectedRuns.Count > 1)
            {
                ClearReportTab();
                BuildPageComparisonTable(queryColumnSelectedValue.SelectedValue.ToString());
            }
        }
        #endregion
        // -- Perfmon TreeView tab handlers ---------------------------------------------------
        #region PERFMON
        private void tvPerfmonCounters_Expanded(object sender, RoutedEventArgs e)
        {
            PerfmonNodeExpandedEventHndler(e);
        }

        private void tvPerfmonCounters_Selected(object sender, RoutedEventArgs e)
        {
            HandleNodeItemSelected(e);
        }

        private void btnLoadPerfCounters_Click(object sender, RoutedEventArgs e)
        {
            LoadPerfmonCounters();
        }

        private void btnExportPerfCounters_Click(object sender, RoutedEventArgs e)
        {
            ExportPerfmonCounters();
        }

        private void btnImportPerfCounters_Click(object sender, RoutedEventArgs e)
        {
            ImportPerfmonCounters();
        }

        private void btnPerfmonCountsForRun_Click(object sender, RoutedEventArgs e)
        {
            getPerfmonCountsForRun();
        }
        #endregion

        private void temp()
        {

        }

    }

    public enum RunListHighlighting
    {
        NoRunsHighlighted = 0,

        SingleRunHighlighted = 1,

        MultipleRunsHighlighted = 2
    };

    public enum RunsToRetrieve
    {
        TodayOnly = 0,

        SelectedDay = 1,

        SelectedRuns = 2,

        SelectedRange = 3
    };

    public enum currentTableType
    {
        Test = 0,

        Transaction = 1,

        Page = 2,

        Perfmon = 3
    };
}
